package net.bxx2004.zephyr;

import net.bxx2004.zephyr.key.KeyBinding;
import net.bxx2004.zephyr.media.MusicPlayer;
import net.bxx2004.zephyr.network.MessageBox;
import net.bxx2004.zephyr.network.MessageListener;
import net.bxx2004.zephyr.network.TMessage;
import net.fabricmc.api.ModInitializer;
import net.minecraft.client.MinecraftClient;
import net.minecraft.entity.player.PlayerEntity;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.*;
import java.net.URL;
import java.net.URLConnection;

public class Zephyr extends MessageListener implements ModInitializer {
    public static final Logger LOGGER = LoggerFactory.getLogger("zephyr");
    public static final String CACHE_PATH = File.listRoots()[0].getPath() + "zephyr";
    //功能
    public static final MusicPlayer MUSIC_PLAYER = new MusicPlayer();
    public static TMessage message;
    @Override
    public void onInitialize() {
        register();
        message = new TMessage("zephyr:zephyr");
        LOGGER.info("zephyr Enable");
        setUP();
    }
    public void setUP(){
        File file = new File(CACHE_PATH + "/music");
        if (!file.exists()){
            file.mkdirs();
        }
    }
    @Override
    public void receive(PlayerEntity player, MessageBox box) {
        if (box.getNode("type").equalsIgnoreCase("keyBinding")){
            new KeyBinding(Integer.parseInt(box.getNode("slot")),box.getNode("name"));
        }
        if (box.getNode("type").equalsIgnoreCase("music")){
            if (box.getNode("state").equalsIgnoreCase("start")){
                MUSIC_PLAYER.play(box.getNode("url"));
            }else {
                MUSIC_PLAYER.stop();
            }
        }

    }
    public static void outFile(String path,String outPath){
        try {
            URL url = Zephyr.class.getClassLoader().getResource(path);
            URLConnection connection = url.openConnection();
            connection.setUseCaches(false);
            InputStream is = connection.getInputStream();
            File f = new File(outPath);// 指定输出文件
            File fp = new File(f.getParent());// 输出文件的父目录
            if (!fp.exists()) {// 父目录不存在时先创建
                fp.mkdirs();
            }
            if (!f.exists()) {// 文件不存在时先创建
                try {
                    f.createNewFile();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            OutputStream os = new FileOutputStream(f);// 创建输出流
            int index = 0;// 当前读取的位数
            byte[] bytes = new byte[1024];
            while ((index = is.read(bytes)) != -1) {
                os.write(bytes, 0, index);
            }
            os.flush();
            os.close();
            is.close();
        }catch (Exception e){
            e.printStackTrace();
        }
    }
}
